package com.cfswt.tasksystem.security;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomRememberMeServices extends PersistentTokenBasedRememberMeServices {

    public CustomRememberMeServices(String key, UserDetailsService userDetailsService, PersistentTokenRepository tokenRepository) {
        super(key, userDetailsService, tokenRepository);
        setParameter("rememberMe"); // 设置前端传递的 rememberMe 参数名
    }

    // 重写 onLoginSuccess 方法，控制是否生成 Remember Me token
    @Override
    protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
        String rememberMeParam = request.getParameter(getParameter());
        boolean isRememberMe = rememberMeParam != null && rememberMeParam.equalsIgnoreCase("true");
        if (isRememberMe) {
            super.onLoginSuccess(request, response, successfulAuthentication); // 调用父类的逻辑生成 token 和 cookie
        } else {
            logger.debug("Remember-me login not requested, skipping token creation.");
        }
    }

    // 可选：自定义 loginSuccess 的扩展方法，供控制器显式调用
    public void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication, boolean rememberMe) {
        if (rememberMe) {
            super.onLoginSuccess(request, response, successfulAuthentication);
        } else {
            logger.debug("Explicit Remember-me not requested.");
        }
    }
}
